package com.lyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lyj.exception.BaseException;
import com.lyj.mapper.FamilyMapper;
import com.lyj.mapper.FamilyMemberMapper;
import com.lyj.mapper.UserMapper;
import com.lyj.pojo.Family;
import com.lyj.pojo.FamilyMember;
import com.lyj.pojo.User;
import com.lyj.pojo.dto.UserUpdateDTO;
import com.lyj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private FamilyMapper familyMapper;

    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    /**
     *登录
     */
    @Override
    public Integer login(String username, String password) {
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda()
                .eq(User::getUsername,username));
        if(user == null){
            throw new BaseException("用户不存在");
        }
        if(user.getPasswordHash().equals(password)){
            return user.getUserId();
        }
        throw new BaseException("登陆失败");
    }

    /**
     * 用户注册实现
     */
    @Transactional // 事务保证，确保用户和家庭关系同时创建
    @Override
    public Integer register(String username, String password, String invitationCode) {
        // 1. 检查用户名是否已存在
        User existingUser = userMapper.selectOne(new QueryWrapper<User>()
                .lambda().eq(User::getUsername, username));
        if (existingUser != null) {
            throw new BaseException("用户名已存在");
        }

        // 2. 创建新用户
        User user = new User();
        user.setUsername(username);
        user.setPasswordHash(password);
        user.setInvitationCode(invitationCode);
        userMapper.insert(user);
        Integer userId = user.getUserId(); // 获取自增ID

        // 3. 处理家庭关系
        if (invitationCode != null && !invitationCode.isEmpty()) {
            // 3.1 有邀请码 - 加入已有家庭（作为普通成员）
            Family family = familyMapper.selectByShareCode(invitationCode);
            if (family == null) {
                throw new BaseException("邀请码无效");
            }

            // 创建家庭成员关系
            FamilyMember member = new FamilyMember();
            member.setFamilyId(family.getFamilyId());
            member.setUserId(userId);
            member.setRole("普通成员");
            familyMemberMapper.insert(member);
        } else {
            // 3.2 无邀请码 - 创建新家庭（作为管理员）
            Family family = new Family();
            family.setFamilyName(username + "的家庭");
            family.setShareCode(generateShareCode()); // 生成唯一邀请码
            familyMapper.insert(family);

            // 创建家庭成员关系（管理员）
            FamilyMember member = new FamilyMember();
            member.setFamilyId(family.getFamilyId());
            member.setUserId(userId);
            member.setRole("管理员");
            familyMemberMapper.insert(member);
        }

        return userId;
    }

    @Override
    public void updateUserProfile(UserUpdateDTO userUpdateDTO) {
        // 验证用户是否存在
        User user = userMapper.selectById(userUpdateDTO.getUserId());
        if (user == null) {
            throw new BaseException("用户不存在");
        }

        // 构建更新条件
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userUpdateDTO.getUserId())
                .set("nickname", userUpdateDTO.getNickname());  // 手动指定更新字段

        userMapper.update(null, updateWrapper);
    }

    /**
     * 生成8位唯一家庭邀请码
     */
    private String generateShareCode() {
        String code = UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        // 检查邀请码是否已存在
        if (familyMapper.selectByShareCode(code) != null) {
            return generateShareCode(); // 递归生成新的
        }
        return code;
    }
}
